//
//  NSFileManager+LLAppFileManager.m
//  live.ly
//
//  Created by bob on 16/7/14.
//  Copyright © 2016年 musical.ly. All rights reserved.
//

#import "NSFileManager+LLAppFileManager.h"


@implementation NSFileManager (LLAppFileManager)

- (NSString *)publicDataPath
{
    @synchronized([NSFileManager class])
    {
        static NSString *path = nil;
        if (!path) {
            //user documents folder
            path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

            //retain path
            path = [[NSString alloc] initWithString:path];
        }
        return path;
    }
}

- (NSString *)privateDataPath
{
    @synchronized([NSFileManager class])
    {
        static NSString *path = nil;
        if (!path) {
            //application support folder
            path = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) lastObject];

#ifndef __IPHONE_OS_VERSION_MAX_ALLOWED

            //append application name on Mac OS
            NSString *identifier = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleNameKey];
            path = [path stringByAppendingPathComponent:identifier];

#endif

            //create the folder if it doesn't exist
            if (![self fileExistsAtPath:path]) {
                [self createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:NULL];
            }

            //retain path
            path = [[NSString alloc] initWithString:path];
        }
        return path;
    }
}

- (NSString *)cacheDataPath
{
    @synchronized([NSFileManager class])
    {
        static NSString *path = nil;
        if (!path) {
            //cache folder
            path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

#ifndef __IPHONE_OS_VERSION_MAX_ALLOWED

            //append application bundle ID on Mac OS
            NSString *identifier = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleIdentifierKey];
            path = [path stringByAppendingPathComponent:identifier];

#endif

            //create the folder if it doesn't exist
            if (![self fileExistsAtPath:path]) {
                [self createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:NULL];
            }

            //retain path
            path = [[NSString alloc] initWithString:path];
        }
        return path;
    }
}


- (NSString *)temporaryDataPath
{
    static NSString *path = nil;
    if (!path) {
        //temporary directory (shouldn't change during app lifetime)
        path = NSTemporaryDirectory();

        //apparently NSTemporaryDirectory() can return nil in some cases
        if (!path) {
            path = [[self cacheDataPath] stringByAppendingPathComponent:@"Temporary Files"];
        }

        //retain path
        path = [[NSString alloc] initWithString:path];
    }
    return path;
}


- (NSString *)workplacePath
{
    NSString *path = [[self privateDataPath] stringByAppendingPathComponent:@"workplace"];
    [self createDirectoryIfNeeded:path];
    return path;
}

- (NSString *)castVideosPath
{
    NSString *path = [[self privateDataPath] stringByAppendingPathComponent:@"castVideosPath"];
    [self createDirectoryIfNeeded:path];
    return path;
}

- (NSString *)discoverNavigateConfigsPath
{
    NSString *path = [[self privateDataPath] stringByAppendingString:@"discoverNavigatePath"];
    [self createDirectoryIfNeeded:path];
    return path;
}

- (void)cleanWorkspace
{
    [self cleanDirectory:[self workplacePath]];
}

- (void)cleanCastVideos
{
    [self cleanDirectory:[self castVideosPath]];
}

- (void)cleanLivelyCache
{
    [self cleanDirectory:[self cacheDataPath]];
}

- (NSString *)userAvatarPath
{
    NSString *path = [[self privateDataPath] stringByAppendingString:@"userAvatars"];
    [self createDirectoryIfNeeded:path];
    return path;
}

- (NSString *)groupAvatarPath
{
    NSString *path = [[self privateDataPath] stringByAppendingPathComponent:@"groupAvatars"];
    [self createDirectoryIfNeeded:path];
    return path;
}

- (void)cleanGroupAvatars
{
    [self cleanDirectory:[self groupAvatarPath]];
}


#pragma mark - Helper

- (unsigned long long int)folderSize:(NSString *)folderPath
{
    //NSError* error;

    NSDirectoryEnumerator *fileEnumerator = [self enumeratorAtURL:[NSURL fileURLWithPath:folderPath]
                                       includingPropertiesForKeys:@[ NSFileSize ]
                                                          options:NSDirectoryEnumerationSkipsHiddenFiles | NSDirectoryEnumerationSkipsSubdirectoryDescendants
                                                     errorHandler:NULL];
    unsigned long long totalSize = 0;
    for (NSURL *fileURL in fileEnumerator) {
        NSNumber *fileSize;
        [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL];
        totalSize += [fileSize unsignedLongLongValue];
    }
    return totalSize;
}

- (void)createDirectoryIfNeeded:(NSString *)directoryPath
{
    //create the folder if it doesn't exist
    if (![self fileExistsAtPath:directoryPath]) {
        [self createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:NULL];
    }
}

- (void)cleanDirectory:(NSString *)directoryPath
{
    NSURL *bundleURL = [NSURL fileURLWithPath:directoryPath];


    NSDirectoryEnumerator *enumerator = [self enumeratorAtURL:bundleURL
                                   includingPropertiesForKeys:@[ NSURLNameKey, NSURLIsDirectoryKey ]
                                                      options:NSDirectoryEnumerationSkipsHiddenFiles
                                                 errorHandler:^BOOL(NSURL *url, NSError *error) {
                                                     DDLogError(@"[Error] %@ (%@)", error, url);
                                                     return YES;
                                                 }];

    NSMutableArray *mutableFileURLs = [NSMutableArray array];

    NSMutableArray *mutableDirectoryURLs = [NSMutableArray array];

    for (NSURL *fileURL in enumerator) {
        NSString *filename;
        [fileURL getResourceValue:&filename forKey:NSURLNameKey error:nil];

        NSNumber *isDirectory;
        [fileURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil];

        //        // Skip directories with '_' prefix, for example
        //        if ([filename hasPrefix:@"_"] && [isDirectory boolValue])
        //        {
        //            [enumerator skipDescendants];
        //            continue;
        //        }

        if (![isDirectory boolValue]) {
            [mutableFileURLs addObject:fileURL];
        } else {
            [mutableDirectoryURLs addObject:fileURL];
        }
    }

    for (NSURL *url in mutableFileURLs) {
        NSString *filePath = [url path];
        [self removeItemAtPath:filePath error:nil];
    }

    //    for (NSURL *url in mutableDirectoryURLs) {
    //        NSString *filePath = [url path];
    //        [self removeItemAtPath:filePath error:nil];
    //    }
}

+ (NSDictionary *)attributesOfItemAtPath:(NSString *)path error:(NSError **)error
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL fileExists = [fileManager fileExistsAtPath:path];
    if (!fileExists) {
        return nil;
    }
    return [fileManager attributesOfItemAtPath:path error:error];
}

+ (unsigned long long)fileSize:(NSString *)path error:(NSError **)error
{
    NSDictionary *attr = [self attributesOfItemAtPath:path error:error];
    if (attr) {
        return attr.fileSize;
    } else {
        return 0;
    }
}


@end
